import { ref } from "vue";
import { TableField, TableUrl } from "@/models/TableSetting";
import { Menu } from "@/models/developer/Menu";

export function menuBackendApiRelationSubmitForm() {
  /**
   * 申明响应式表单
   */
  const submitFormRef = ref();

  /**
   * 申明提交表单的内容
   */
  const submitForm = ref({} as Menu);

  /**
   * 用到的url
   */
  const url = {
    refreshUrl: "/basic-request/Menu",
    modifyingSingleUrl: "/basic-request/Menu",
    deleteUrl: "/basic-request/Menu/batchDelete",
  } as TableUrl;

  /**
   * 表字段列表
   */
  const tableFieldList = [
    {
      filedName: "parentId",
      label: "父id",
      width: 100,
    },
    {
      filedName: "menuOrders",
      label: "菜单排序",
      width: 120,
    },
    {
      filedName: "path",
      label: "路径",
      width: 260,
    },
    {
      filedName: "parentTitle",
      label: "父菜单",
      width: 200,
    },
    {
      filedName: "title",
      label: "标题",
      minWidth: 220,
    },
    {
      filedName: "icon",
      label: "图标",
      width: 180,
    },
    {
      filedName: "createGmt",
      label: "创建时间",
      width: 220,
    },
    {
      filedName: "modifiedGmt",
      label: "修改时间",
      width: 220,
    },
  ] as Array<TableField>;

  /**
   * 校验规则
   */
  const formRules = {
    menuOrders: [
      {
        required: true,
        message: "菜单项不能为空",
        trigger: "blur",
      },
    ],
    path: [
      {
        required: true,
        message: "路径不能为空",
        trigger: "blur",
      },
    ],
    title: [
      {
        required: true,
        message: "标题不能为空",
        trigger: "blur",
      },
    ],
  };

  /**
   * 规范数据
   * @param columnName 列名称
   * @param cellValue 单元格的值
   * @param callback 回调函数
   */
  const dataFormat = (
    columnName: string,
    cellValue: string,
    callback: (value: string) => void
  ) => {
    if (columnName === "createUser") {
      callback(cellValue);
    }
  };

  /**
   * 设置表单的初始值
   * @param formType 表单的类型, 新增/编辑
   * @param row 选中行的值, 编辑时将该值赋给表单.
   */
  const setFormInitValue = (formType: string, row: Menu) => {
    if (undefined !== submitFormRef.value) {
      submitFormRef.value.clearValidate();
    }
    switch (formType) {
      case "insert":
        submitForm.value = {
          parentId: 0,
          menuOrders: 0,
          icon: "",
          path: "",
          title: "",
          createGmt: new Date(),
        } as Menu;
        break;
      case "update":
        submitForm.value = row;
        submitForm.value.modifiedGmt = new Date();
        break;
    }
  };

  /**
   * 提交数据前的校验
   * @param callback 回调函数,将校验结果返还到Table组件中.
   */
  const submitValid = (callback: (value: boolean) => void) => {
    submitFormRef.value
      .validate()
      .then(() => {
        callback(true);
      })
      .catch(() => {
        callback(false);
      });
  };

  return {
    submitFormRef,
    submitForm,
    url,
    tableFieldList,
    formRules,
    dataFormat,
    setFormInitValue,
    submitValid,
  };
}
